import ReconnectingWebSocket from 'reconnecting-websocket';
const Socket = {
    init(token) {    
        let baseUrl = sessionStorage.getItem('wsUrl');
        let wsUrl = `${baseUrl.replace('http', 'ws')}/realtime_events?Token=${encodeURIComponent(token)}`;
        this.WS = new WebSocket(wsUrl);
        // 监听socket连接
        // this.WS.onopen = this.open.bind(this);
        // 监听socket错误信息
        // this.WS.onerror = this.error;
        // 监听socket断开
        // this.WS.onclose = this.close;
        this.state = "offline"
    },
    onOpen (cb) {
        this.WS.onopen = res => {
            console.log("socket连接成功")
            this.state = "online"
            cb('socket连接成功')
        }
    },
    onError (cb) {
        this.WS.onerror = res => {
            console.log("连接错误");
            cb()
        }
    },
    onMessage (cb) {
        this.WS.onmessage = res => {
            try{
                let data = res.data;
                cb(data);
            }catch(e) {
                console.log(e);
            }
        }
    },
    send (params) {
        this.WS.send(params)
    },
    close () {
        this.WS.close();
    },
    onClose (cb) {
        this.WS.onclose = res => {
            console.log("socket已经关闭--->需要重连111");
            this.state = "offline"
            let n = setInterval(()=>{
                console.log('11111')
                this.init(localStorage.getItem("Token"))
                if(this.state == "online") {
                    clearInterval(n)
                }
            }, 5000)
            cb()
        }
    },
}

export default Socket;